package com.ljb.monitorview.monitor3;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ljb.monitorview.R;
import com.squareup.picasso.Picasso;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 新版工艺监控自定义控件
 * Created by ljb on 2017/6/16.
 */

public class MonitorView3 extends FrameLayout {
    private static final String TAG = "MonitorView";

    private int local_width;//实际控件的宽
    private int local_height;//实际控件的高
    private ConfigBean3 mConfig;  //配置信息
    private Context c;//上下文
    private List<MonitorBean3.Copymsg> copymsg; //数据信息
    private List<MonitorBean3.Pos> pos;  //位置点信息
    private ImageView bg;//背景
    private Map<String, View> viewMap = new HashMap<>();//模拟量和数字量的View对象
    public final long TIME_INTERRUPT = 60 * 3;//数据断开状态阈值

    public MonitorView3(@NonNull Context context) {
        this(context, null);
    }

    public MonitorView3(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MonitorView3(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        c = context;
        setWillNotDraw(false);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (oldw == oldh && w > h) {
            //获取控件的大小
            this.local_width = w;
            this.local_height = h;
            Log.e(TAG, "onSizeChanged: MonitorView控件的宽:" + w + ";高:" + h);
        }
    }

    //设置背景
    private void initBg() {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        params.setMargins(0, 0, 0, 0);
        LinearLayout layout = new LinearLayout(c);
        bg = new ImageView(c);
        bg.setLayoutParams(params);
        bg.setScaleType(ImageView.ScaleType.FIT_XY);
        layout.addView(bg);
        addView(layout);

        String bgUrl = mConfig.preUrl + mConfig.bgUrl;
        Log.e(TAG, "initBg: 背景URL:" + bgUrl);
        Picasso.with(c).load(utf8Togb2312(bgUrl)).into(bg);
        Log.e(TAG, "initBg: 设置背景完毕");
    }

    //utf8转gbk的工具
    private String utf8Togb2312(String str) {
        String data = "";
        try {
            for (int i = 0; i < str.length(); i++) {
                char c = str.charAt(i);
                if (c + "".getBytes().length > 1 && c != ':' && c != '/') {
                    data = data + java.net.URLEncoder.encode(c + "", "utf-8");
                } else {
                    data = data + c;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            Log.d(TAG, "utf8Togb2312: 转码后的地址为:" + data);
        }
        return data;
    }

    //增加模拟量控件(动态变化的数字)
    private void addAningog(MonitorBean3.Copymsg msg, MonitorBean3.Pos pos) {
        MonitorBean3.Copymsg.ConfigSet configSet = msg.configSet;
        String moniBeforeText = configSet.moniBeforeText;//前缀
        String moniAfterText = configSet.moniAfterText;//后缀
        String text_Str = moniBeforeText + "$" + moniAfterText;
        Spannable span = getSpannable(moniBeforeText, moniAfterText, text_Str);

        //设置模拟量的位置
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        // TODO: 2017/6/20 模拟量位置适配在此处处理
        int l = (int) (pos.left / 100 * local_width + mConfig.dataX * (1 - pos.left / 100));
        int t = (int) (pos.top / 100 * local_height + mConfig.dataY * (1 - pos.left / 100));
        params.setMargins(l, t, 0, 0);
        LinearLayout layout = new LinearLayout(c);

        TextView textView = new TextView(c);
        textView.setLayoutParams(params);
        textView.setText(span);
        textView.setTextSize(mConfig.dataSize);
        textView.setTextColor(Color.parseColor(mConfig.textColor));
        textView.setTag(R.id.tag_first, moniBeforeText);
        textView.setTag(R.id.tag_second, moniAfterText);

        layout.addView(textView);
        addView(layout);
        viewMap.put(msg.imgprogramId, textView);
        Log.e(TAG, "addAningog: 增加模拟量完毕 " + msg.imgprogramId);
    }

    @NonNull
    private Spannable getSpannable(String moniBeforeText, String moniAfterText, String text_Str) {
        Spannable span = new SpannableString(text_Str);
        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor(mConfig.dataColor));//字体颜色

        //设置模拟量的字体颜色和大小
        span.setSpan(foregroundColorSpan, moniBeforeText.length(), text_Str.length() - moniAfterText.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        return span;
    }

    //增加数字量控件(小圆图)
    private void addDigiting(MonitorBean3.Copymsg msg, MonitorBean3.Pos pos) {
        //设置数字量的位置
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) (msg.childToParentPercent.wpercent * local_width * msg.configSet.scaleSet), (int) (msg.childToParentPercent.hpercent * local_height * msg.configSet.scaleSet));
        // TODO: 2017/6/20 数字量位置适配在此处处理
//        int l = (int) (pos.left / 100 * local_width + mConfig.imageX * (1 - pos.left / 100));
//        int t = (int) (pos.top / 100 * local_height + mConfig.imageY * (1 - pos.top / 100));
        int l = (int) ((pos.left + mConfig.imageX) / 100 * local_width);
        int t = (int) ((pos.top + mConfig.imageY) / 100 * local_height);

        params.setMargins(l, t, 0, 0);

        ImageView imageView = new ImageView(c);
        imageView.setLayoutParams(params);
//        Picasso.with(c).load(utf8Togb2312(mConfig.preUrl + "common/point-r.png")).into(imageView);

        LinearLayout layout = new LinearLayout(c);
        layout.addView(imageView);
        addView(layout);

        String imgprogramId = msg.imgprogramId;
        if (viewMap.containsKey(imgprogramId)) {
            for (int i = 0; i < 20; i++) {
                if (!viewMap.containsKey(imgprogramId + i)) {
                    imgprogramId += i;
                    break;
                }
            }
        }
        viewMap.put(imgprogramId, imageView);
        Log.e(TAG, "addAningog: 增加数字量完毕 " + imgprogramId);
    }

    //增加固定文本显示
    private void addConstantData(MonitorBean3.Copymsg msg, MonitorBean3.Pos pos) {
        //设置固定为本的位置
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        // TODO: 2017/6/20 固定文本位置适配在此处处理
//        int l = (int) (pos.left / 100 * local_width + mConfig.textX * (1 - pos.left / 100));
//        int t = (int) (pos.top / 100 * local_height + mConfig.textY * (1 - pos.left / 100));
        int l = (int) ((pos.left + mConfig.imageX) / 100 * local_width);
        int t = (int) ((pos.top + mConfig.imageY) / 100 * local_height);

        params.setMargins(l, t, 0, 0);
        LinearLayout layout = new LinearLayout(c);

        TextView textView = new TextView(c);
        textView.setLayoutParams(params);
        textView.setTextSize(mConfig.textSize);
        textView.setText(msg.configSet.fontContent);
        textView.setTextColor(Color.parseColor(mConfig.textColor));

        layout.addView(textView);
        addView(layout);
        Log.e(TAG, "addAningog: 增加固定文本完毕");
    }
/***********************************************************************************************/
    /**
     * 为控件添加数据
     *
     * @param monitorBean3
     */
    public void setOSSData(MonitorBean3 monitorBean3) {
        copymsg = monitorBean3.copymsg;
        pos = monitorBean3.pos;
        for (int i = 0; i < copymsg.size(); i++) {
            MonitorBean3.Copymsg msg = copymsg.get(i);
            switch (msg.imgtype) {
                case "zoneOne"://模拟量
                    addAningog(msg, pos.get(i));
                    break;
                case "zoneTwo"://数字量
                    addDigiting(msg, pos.get(i));
                    break;
                case "zoneFour"://文本
                    addConstantData(msg, pos.get(i));
                    break;
                case "zoneThree"://可控变量
                    break;
            }
        }
    }

    /**
     * 设置配置信息
     *
     * @param config
     */
    public void setConfig(ConfigBean3 config) {
        mConfig = config;
        initBg();
    }

    /**
     * 清空控件上的所有点的数据
     */
    public void clearData() {
        removeAllViews();
        copymsg.clear();
        pos.clear();
        viewMap.clear();
    }

    /**
     * 刷新动态数据
     *
     * @param notifyData3
     */
    public void notifyData(NotifyData3 notifyData3) {
        judgeDataStauts(notifyData3);
    }

    /*******************************************************************************************/


    /**
     * 判断当前数据连接状态,如果数据库中最新数据的入库时间戳和当前时间戳做差值,
     * 超过断开阈值则判断为数据断开状态
     */
    private void judgeDataStauts(NotifyData3 notifyData3) {
        long time_data = notifyData3.time;
        long time_now = System.currentTimeMillis() / 1000;
        if (time_now - time_data > TIME_INTERRUPT) {//数据处于断开状态
            Log.e(TAG, "judgeDataSuts: 当前数据状态为: 断开状态");
            switch (notifyData3.interruptmode) {
                case 1://默认显示数据库中的最后一条数据
                    notifyDataInterrupt1(notifyData3.list);//刷新断开状态的数据,断开模式为1
                    break;
                case 2://所有的模拟量显示为0,数字量显示为错误
                    notifyDataInterrupt2(notifyData3.list);//刷新断开状态的数据,断开模式为2
                    break;
                case 3://所有的模拟量显示为空,数字量显示为空
                    notifyDataInterrupt3(notifyData3.list);//刷新断开状态的数据,断开模式为3
                    break;
            }
        } else {//数据处于连接状态
            Log.e(TAG, "judgeDataSuts: 当前数据状态为: 连接状态");
            notifyDataNormal(notifyData3.list);
        }
    }

    //模式3的断开状态
    private void notifyDataInterrupt3(List<NotifyData3.List> lists) {
        for (int i = 0; i < lists.size(); i++) {
            NotifyData3.List list = lists.get(i);
            String key = list.name;
            if (!viewMap.containsKey(key)) {//判断是否包含key
                continue;
            }
            if (viewMap.containsKey(key + 0)) {
                for (int j = 0; j < 20; j++) {
                    if (!viewMap.containsKey(key + j)) {
                        break;
                    }
                    View view = viewMap.get(key + j);
                    String value = list.value;
                    if (view instanceof TextView) {//模拟量
                        notifyAningogNormal((TextView) view, "  ");
                        Log.e(TAG, "notifyDataNormal: 刷新模拟量 " + key);
                    } else if (view instanceof ImageView) {//数字量
                        notifyDigitingInterrupt3(list, (ImageView) view, value);
                        Log.e(TAG, "notifyDataNormal: 刷新数字量 " + key);
                    }
                }
            } else {
                View view = viewMap.get(key);
                String value = list.value;
                if (view instanceof TextView) {//模拟量
                    notifyAningogNormal((TextView) view, "  ");
                    Log.e(TAG, "notifyDataNormal: 刷新模拟量 " + key);
                } else if (view instanceof ImageView) {//数字量
                    notifyDigitingInterrupt3(list, (ImageView) view, value);
                    Log.e(TAG, "notifyDataNormal: 刷新数字量 " + key);
                }
            }
        }
    }

    //模式3的数字量断开状态,隐藏数字量
    private void notifyDigitingInterrupt3(NotifyData3.List list, ImageView view, String value) {
        String imgPath = list.imgPath;
        //复合状态
        if (value.contains("word")) {
            String word = value.replaceAll("word", "");
            if (word.isEmpty()) {
                return;
            }
            String imgPathSub = imgPath.substring(imgPath.indexOf("-") + 1, imgPath.indexOf("."));
            imgPath = imgPath.replaceAll("-" + imgPathSub, "-" + word);
        } else {//单一状态
            switch (value) {
                case "0"://停止状态
                case "1"://运行状态
                case "2"://错误状态
                case "4"://开到关,关到开的中间状态
                case "3"://隐藏状态
                    view.setVisibility(View.INVISIBLE);//隐藏数字量
                    return;
            }
        }
        //加载图片
        view.setVisibility(View.VISIBLE);
        Picasso.with(c).load(utf8Togb2312(mConfig.preUrl + imgPath)).into(view);
    }

    //模式2的断开状态
    private void notifyDataInterrupt2(List<NotifyData3.List> lists) {
        for (int i = 0; i < lists.size(); i++) {
            NotifyData3.List list = lists.get(i);
            String key = list.name;
            if (!viewMap.containsKey(key)) {//判断是否包含key
                continue;
            }
            if (viewMap.containsKey(key + 0)) {
                for (int j = 0; i < 20; j++) {
                    if (!viewMap.containsKey(key + j)) {
                        break;
                    }
                    View view = viewMap.get(key + j);
                    String value = list.value;
                    if (view instanceof TextView) {//模拟量
                        notifyAningogNormal((TextView) view, "0");
                        Log.e(TAG, "notifyDataNormal: 刷新模拟量 " + key);

                    } else if (view instanceof ImageView) {//数字量
                        notifyDigitingInterrupt2(list, (ImageView) view, value);
                        Log.e(TAG, "notifyDataNormal: 刷新数字量 " + key);
                    }
                }
            } else {
                View view = viewMap.get(key);
                String value = list.value;
                if (view instanceof TextView) {//模拟量
                    notifyAningogNormal((TextView) view, "0");
                    Log.e(TAG, "notifyDataNormal: 刷新模拟量 " + key);

                } else if (view instanceof ImageView) {//数字量
                    notifyDigitingInterrupt2(list, (ImageView) view, value);
                    Log.e(TAG, "notifyDataNormal: 刷新数字量 " + key);
                }
            }
        }
    }

    //模式1的断开状态
    private void notifyDataInterrupt1(List<NotifyData3.List> list) {
        notifyDataNormal(list);
    }

    //模式2的数字量的断开状态,所有数字量显示停止状态
    private void notifyDigitingInterrupt2(NotifyData3.List list, ImageView view, String value) {
        String imgPath = list.imgPath;
        //复合状态
        if (value.contains("word")) {
            String word = value.replaceAll("word", "");
            if (word.isEmpty()) {
                return;
            }
            String imgPathSub = imgPath.substring(imgPath.indexOf("-") + 1, imgPath.indexOf("."));
            imgPath = imgPath.replaceAll("-" + imgPathSub, "-" + word);
        } else {//单一状态
            switch (value) {
                case "0"://停止状态
                case "1"://运行状态
                case "2"://错误状态
                case "4"://开到关,关到开的中间状态
                    imgPath = imgPath.replaceAll("-s", "-f");
                    imgPath = imgPath.replaceAll("-r", "-f");
                    imgPath = imgPath.replaceAll("-b", "-f");
                    break;
                case "3"://隐藏状态
                    view.setVisibility(View.INVISIBLE);
                    return;
            }
        }
        //加载图片
        view.setVisibility(View.VISIBLE);
        Picasso.with(c).load(utf8Togb2312(mConfig.preUrl + imgPath)).into(view);
    }

    //刷新正常状态的数据
    private void notifyDataNormal(List<NotifyData3.List> lists) {
        for (int i = 0; i < lists.size(); i++) {
            NotifyData3.List list = lists.get(i);
            String key = list.name;
            if (!viewMap.containsKey(key)) {//判断是否包含key
                continue;
            }

            if (viewMap.containsKey(key + 0)) {
                for (int j = 0; i < 20; j++) {
                    if (!viewMap.containsKey(key + j)) {
                        break;
                    }
                    View view = viewMap.get(key + j);
                    String value = list.value;
                    if (view instanceof TextView) {//模拟量
                        notifyAningogNormal((TextView) view, value);
                        Log.e(TAG, "notifyDataNormal: 刷新模拟量 " + key);

                    } else if (view instanceof ImageView) {//数字量
                        notifyDigitingNormal(list, (ImageView) view, value);
                        Log.e(TAG, "notifyDataNormal: 刷新数字量 " + key);
                    }
                }
            } else {
                View view = viewMap.get(key);
                String value = list.value;
                if (view instanceof TextView) {//模拟量
                    notifyAningogNormal((TextView) view, value);
                    Log.e(TAG, "notifyDataNormal: 刷新模拟量 " + key);

                } else if (view instanceof ImageView) {//数字量
                    notifyDigitingNormal(list, (ImageView) view, value);
                    Log.e(TAG, "notifyDataNormal: 刷新数字量 " + key);
                }
            }
        }
    }

    //刷新模拟量
    private void notifyAningogNormal(TextView view, String value) {
        String s_;
        int index = value.indexOf('.');
        if (index > 0) {
            s_ = value.substring(0, index + 2);
        } else {
            s_ = value + ".00";
        }
        String moniBeforeText = (String) view.getTag(R.id.tag_first);//前缀
        String moniAfterText = (String) view.getTag(R.id.tag_second);//后缀
        Spannable spannable = getSpannable(moniBeforeText, moniAfterText, moniBeforeText + s_ + moniAfterText);
        view.setText(spannable);
    }

    //刷新数字量的状态
    private void notifyDigitingNormal(NotifyData3.List list, ImageView view, String value) {
        String imgPath = list.imgPath;
        //复合状态
        if (value.contains("word")) {
            String word = value.replaceAll("word", "");
            if (word.isEmpty()) {
                return;
            }
            String imgPathSub = imgPath.substring(imgPath.indexOf("-") + 1, imgPath.indexOf("."));
            imgPath = imgPath.replaceAll("-" + imgPathSub, "-" + word);
        } else {//单一状态
            switch (value) {
                case "0"://停止状态
                    imgPath = imgPath.replaceAll("-r", "-s");
                    imgPath = imgPath.replaceAll("-f", "-s");
                    break;
                case "1"://运行状态
                    imgPath = imgPath.replaceAll("-s", "-r");
                    imgPath = imgPath.replaceAll("-f", "-r");
                    break;
                case "2"://错误状态
                    imgPath = imgPath.replaceAll("-s", "-f");
                    imgPath = imgPath.replaceAll("-r", "-f");
                    break;
                case "3"://隐藏状态
                    view.setVisibility(View.INVISIBLE);
                    return;
                case "4"://开到关,关到开的中间状态
                    imgPath = imgPath.replaceAll("-s", "-b");
                    imgPath = imgPath.replaceAll("-r", "-b");
                    imgPath = imgPath.replaceAll("-f", "-b");
                    break;
            }
        }
        //加载图片
        view.setVisibility(View.VISIBLE);
        Picasso.with(c).load(utf8Togb2312(mConfig.preUrl + imgPath)).into(view);
    }
}






































